package org.cgs.web.server.registration;

import java.io.IOException;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.log4j.Logger;
import org.cgs.web.database.DatabaseConnector;

public final class EditSchool extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = Logger.getLogger(EditSchool.class);

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Get School info from the web page
        String courseCode = (String)request.getSession().getAttribute("courseCode");
        boolean isInstructor = request.getParameter("isInstructor") == null ? true : Boolean.parseBoolean(request.getParameter("isInstructor"));
        String name = request.getParameter("name") == null ? "" : request.getParameter("name");
        String address = request.getParameter("address") == null ? "" : request.getParameter("address");
        String contact = request.getParameter("contact") == null ? "" : request.getParameter("contact");
        String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone");
        int numStudents = request.getParameter("numStudents") == null ? 0 : Integer.parseInt(request.getParameter("numStudents"));
        String details = request.getParameter("details") == null ? "" : request.getParameter("details");
        String[] times = request.getParameterValues("times") == null ? new String[] {} : request.getParameterValues("times");
        String isFar = request.getParameter("isFar") == null ? "" : request.getParameter("isFar");

        // See if the school name exists in the database
        boolean errorOccurred = false;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            con = DatabaseConnector.getInstance().getConnection();
            pstmt = con.prepareStatement("SELECT numStudents, address, contact, phone, details, isFar FROM school WHERE name=? AND courseCode=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
            pstmt.setString(1, name);
            pstmt.setString(2, courseCode);
            rs = pstmt.executeQuery();

            // If there is an entry in first spot of result set, school exists
            if (rs.next())
            {
                if (numStudents != rs.getInt("numStudents"))
                {
                    rs.updateInt("numStudents", numStudents);
                }

                if (!address.equalsIgnoreCase(rs.getString("address")))
                {
                    rs.updateString("address", address);
                }

                if (!contact.equalsIgnoreCase(rs.getString("contact")))
                {
                    rs.updateString("contact", contact);
                }

                if (!phone.equalsIgnoreCase(rs.getString("phone")))
                {
                    rs.updateString("phone", phone);
                }

                if (!details.equalsIgnoreCase(rs.getString("details")))
                {
                    rs.updateString("details", details);
                }

                if (!isFar.equalsIgnoreCase(rs.getString("isFar")))
                {
                    rs.updateString("isFar", isFar);
                }

                rs.updateRow();

                try
                {
                    // Close the ResultSet
                    rs.close();
                }
                catch (Exception e)
                {
                    errorOccurred = true;
                    LOGGER.error("Exception cleaning up result set", e);
                }

                try
                {
                    // Close the PreparedStatement
                    pstmt.close();
                }
                catch (Exception e)
                {
                    errorOccurred = true;
                    LOGGER.error("Exception cleaning up prepared statement", e);
                }

                pstmt = con.prepareStatement("DELETE FROM school_times WHERE courseCode=? AND name=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
                pstmt.setString(1, courseCode);
                pstmt.setString(2, name);
                pstmt.executeUpdate();

                try
                {
                    // Close the PreparedStatement
                    pstmt.close();
                }
                catch (Exception e)
                {
                    errorOccurred = true;
                    LOGGER.error("Exception cleaning up prepared statement", e);
                }

                // Insert the school times
                pstmt = con.prepareStatement("INSERT INTO school_times VALUES (?, ?, ?)");
                for (String time : times)
                {
                    pstmt.setString(1, name);
                    pstmt.setString(2, time);
                    pstmt.setString(3, courseCode);
                    pstmt.executeUpdate();
                } // End for loop
            } // End else
        } // End try block
        catch (SQLException e)
        {
            errorOccurred = true;
            LOGGER.error("Exception thrown attempting to edit a school", e);
        } // End catch block
        finally
        {
            try
            {
                // Close the ResultSet
                if (rs != null)
                {
                    rs.close();
                }
            }
            catch (Exception e)
            {
                errorOccurred = true;
                LOGGER.error("Exception cleaning up result set", e);
            }

            try
            {
                // Close the PreparedStatement
                if (pstmt != null)
                {
                    pstmt.close();
                }
            }
            catch (Exception e)
            {
                errorOccurred = true;
                LOGGER.error("Exception cleaning up prepared statement", e);
            }

            try
            {
                // Close the connection
                if (con != null)
                {
                    con.close();
                }
            }
            catch (Exception e)
            {
                errorOccurred = true;
                LOGGER.error("Exception cleaning up connection to the database", e);
            }
        }

        if (errorOccurred)
        {
            request.getRequestDispatcher("").forward(request, response);
        }
        else
        {
            if (isInstructor)
            {
                response.sendRedirect("instructor/schools/school.jsp?id=" + name);
            }
            else
            {
                response.sendRedirect("school/school.jsp");
            }
        }
    } // End method
} // End class
